package itsm.isperp.module.utils;

import itsm.isperp.module.response.ExcelModel;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Description
 * @Project isperp-itss
 * @Author ZhiYue
 * @Date 2020/5/27 9:37
 */
public class ExcelUtils {

    /**
      * Excel 构建工具
      * @Description 传入ExcelModel 对象返回 workBook 对象
      * @Auth ZhiYue
      * @Date 2020/5/27 13:41
    */
    public static Workbook excelStream(ExcelModel excelModel)
            throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        // 1.创建 xlsx 的 excel 对象
        Workbook workbook = new SXSSFWorkbook();
        // 2.生成 Sheet 对象
        Sheet sheet = workbook.createSheet();
        // 3.Sheet 的配置
        for(int i=0; i<excelModel.getThs().size(); i++) {
            if(i == 1) {
                sheet.setColumnWidth(i, 4000);
            }else {
                sheet.setColumnWidth(i, 3000);
            }
        }
        sheet.setDefaultRowHeight((short)400);
        CellStyle style = workbook.createCellStyle();
//        style.setAlignment(CellStyle.ALIGN_CENTER);
        Font font = workbook.createFont();
//        font.setBoldweight(Font.BOLDWEIGHT_BOLD);
        font.setFontName("Arial");
        style.setFont(font);
        // 4.写入数据
        Row head = sheet.createRow(0);
        for(int i=0; i<excelModel.getThs().size(); i++) {
            Cell th = head.createCell(i);
            th.setCellValue((String)excelModel.getThs().get(i));
            th.setCellStyle(style);
        }
        for(int i=0;i<excelModel.getTrs().size(); i++) {
            Row tr = sheet.createRow(i+1);
            Class clazz = excelModel.getTrs().get(i).getClass();
            ExcelModel excelModel1 = (ExcelModel) excelModel.getTrs().get(i);
            Field[] fields = clazz.getDeclaredFields();
            for(int j=0; j<fields.length; j++) {
                String name = fields[j].getName();
                name = name.substring(0,1).toUpperCase() + name.substring(1);

                Method m = clazz.getMethod("get" + name);
                String value = (String) m.invoke(excelModel1);
                Cell td = tr.createCell(j);
                td.setCellValue(value);
            }
        }
        return workbook;
    }

    /**
     * 依据 excel 模板获取excel的workbook对象
     * @param map 传入的参数,参数名称要和模板文件中定义的参数名称要一致
     * @param fileTemplate 模板文件的路径
     * @return Workbook
     */
 /*   public static Workbook getExcelStream(OutputStream os, Map<String, String> map, String fileTemplate) throws IOException, InvalidFormatException {
        InputStream is = new FileInputStream(fileTemplate);
        Context context = new Context();
        context.putVar("map", map);
        JxlsHelper.getInstance().processTemplate(is, os, context);
        return null;
    }*/
}
